<template>
  <el-card>
    <el-form inline>
      <el-form-item>
        <el-input placeholder="用户名" v-model="username" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="getUserList"
          >查询</el-button
        >
        <el-button @click="reset">清空</el-button>
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="showSaveUser">添加</el-button>
    <el-button type="danger">批量删除</el-button>

    <el-table :data="userList" border class="user-table">
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" align="center" label="序号" />
      <el-table-column prop="nickName" label="用户昵称" />
      <el-table-column label="角色列表" prop="roleName" />
      <el-table-column label="创建时间" prop="gmtCreate" />
      <el-table-column label="更新时间" prop="gmtModified" />
      <el-table-column label="操作" width="200" fixed="right">
        <template v-slot="{ row }">
          <el-tooltip content="分配角色权限" placement="top" effect="light">
            <el-button
              type="primary"
              :icon="UserFilled"
              size="small"
              @click="showAssignRole(row.id, row.username)"
            />
          </el-tooltip>
          <el-tooltip content="修改角色" placement="top" effect="light">
            <el-button type="warning" :icon="Edit" size="small" />
          </el-tooltip>
          <el-tooltip content="删除角色" placement="top" effect="light">
            <el-button type="danger" :icon="Delete" size="small" />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:currentPage="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 12, 15]"
      small
      layout=" prev, pager, next, jumper,total, sizes"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-dialog v-model="dialogVisible" title="添加用户">
      <el-form
        label-width="120px"
        :model="userFormData"
        ref="resFromRef"
        :rules="rules"
      >
        <el-form-item label="用户名" prop="username">
          <el-input placeholder="用户名" v-model="userFormData.username" />
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickName">
          <el-input placeholder="用户昵称" v-model="userFormData.nickName" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input placeholder="密码" v-model="userFormData.password" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveUser">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="assignRoleVisible" title="分配用户角色">
      <el-form label-width="100px">
        <el-form-item label="用户名"> {{ selectedUser.username}} </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange($event as boolean)"
            >全选</el-checkbox
          >
          <el-checkbox-group
            v-model="assignRoleList"
            @change="handleCheckedCitiesChange"
          >
            <!-- label代表选中的值 -->
            <el-checkbox
              v-for="role in roleList"
              :key="role.id"
              :label="role.id"
              >{{ role.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="assignUser">确定</el-button>
          <el-button @click="assignRoleVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "XUser",
};
</script>

<script lang="ts" setup>
import { Search, Edit, Delete, UserFilled } from "@element-plus/icons-vue";
import { ref, onMounted, reactive } from "vue";
import {
  getUserListApi,
  saveUserApi,
  getUserRoleApi,
  doAssignUserApi,
} from "@/api/acl/user";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import type { RoleList } from "@/api/acl/model/userModel";

const userList = ref([]);
const currentPage = ref(1);
const username = ref("");
const pageSize = ref(5);
const total = ref(1);

const dialogVisible = ref(false);
// 添加fromDOM元素
const resFromRef = ref<FormInstance>();
// 添加模态框
const userFormData = reactive({
  username: "",
  nickName: "",
  password: "",
});

// 用户分配角色
const assignRoleVisible = ref(false);
// 是否全选（需要请求数据计算）
const checkAll = ref(false);
// 是否半选（需要请求数据计算）
const isIndeterminate = ref(false);

// 所有角色列表
const roleList = ref<RoleList>([]);
// 选中的角色id列表
const assignRoleList = ref<number[]>([]);
// 选中用户的名字
const selectedUser = ref({
  id: 0,
  username: "",
});

//

const showAssignRole = async (id: number, username: string) => {
  const result = await getUserRoleApi(id);
  // 选中用户的名字
  selectedUser.value = {
    id,
    username,
  };
  assignRoleVisible.value = true;
  //所有角色列表
  roleList.value = result.allRolesList;
  // 请求回来的数据[]里面是对象，而我们需要的是id,格式化
  assignRoleList.value = result.assignRoles.map((item) => item.id); //number[]

  // 半选状态
  isIndeterminate.value =
    assignRoleList.value.length === roleList.value.length ||
    assignRoleList.value.length === 0
      ? false
      : true;
  //全选状态
  checkAll.value = assignRoleList.value.length === roleList.value.length;
};

// 全选
const handleCheckAllChange = (val: boolean) => {
  isIndeterminate.value = false;
  if (val) {
    //全选
    assignRoleList.value = roleList.value.map((role) => role.id);
    return;
  }
  // 全不选
  assignRoleList.value = [];
};
// 单个复选框触发
const handleCheckedCitiesChange = () => {
  if (
    assignRoleList.value.length === roleList.value.length ||
    assignRoleList.value.length === 0
  ) {
    isIndeterminate.value = false;
  } else {
    isIndeterminate.value = true;
  }
};

const assignUser = async () => {
  await doAssignUserApi(selectedUser.value.id, assignRoleList.value);
  ElMessage.success("分配用户角色成功");
  assignRoleVisible.value = false;
  getUserList();
};

// 一上来发送请求
onMounted(() => {
  getUserList();
});

// 发送获取用户列表请求
const getUserList = async () => {
  const result = await getUserListApi({
    page: currentPage.value,
    limit: pageSize.value,
    username: username.value,
  });
  userList.value = result.items;
  total.value = result.total;
};

const reset = () => {
  username.value = "";
  getUserList();
};

const rules = reactive<FormRules>({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  nickName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入用户名", trigger: "blur" }],
});

// 显示添加框
const showSaveUser = () => {
  userFormData.username = "";
  userFormData.nickName = "";
  userFormData.password = "";

  dialogVisible.value = true;
};

// 添加用户
const saveUser = () => {
  resFromRef.value?.validate(async (valid) => {
    if (valid) {
      await saveUserApi(userFormData);
      ElMessage.success("添加成功");
      dialogVisible.value = false;
      getUserList();
    } else {
      console.log("输入有误！");
      return false;
    }
  });
};

const handleSizeChange = (newPageSize: number) => {
  pageSize.value = newPageSize;
  getUserList();
};
const handleCurrentChange = (newCurrentPage: number) => {
  currentPage.value = newCurrentPage;
  getUserList();
};
</script>

<style scoped>
.user-table {
  margin: 20px 0;
}
</style>